#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<time.h>
#include<sqlite3.h>
#include<signal.h>

#include"zlog.h"
#include"socket_connect.h"
#include"iniparser_get.h"
#include"ds18b20.h"
#include"get_device_id.h"
#include"pack_json.h"
#include"database.h"

int     sig_stop = 0;

void signal_stop(int signum)
{

    if (signum == SIGINT)
    sig_stop = 1;

}

int main(int argc, char **argv)
{
    sqlite3      *db;

    int           port = 0;
    int           connfd = -1;
    int           rowid = 1;
    int           rv = -1;
    int           ret = -1; 
    int           len;
    int           number[1024];
    int           i;
    int           rc = -1;
        
    float         tmp;
    
    char         *errmsg;
    char         device_id[1024];  /*rpi#002*/
    char         serverip[1024];
    char	     *db_file="./test.db";
    char         buf[1024];
    char 		conf_file;//iniparser
    char        *zlog_conf_file = "./client_zlog.conf";//zlog

    struct sockaddr_in serv_addr;
    
    time_t		last_time;
    time_t		now_time;
    

    memset(buf, 0, sizeof(buf));
    memset(serverip, 0, sizeof(serverip));
    memset(number, 0, sizeof(number));
    memset(device_id, 0, sizeof(device_id));
    
    zlog_category_t     *zg = NULL;
    rc = zlog_init(zlog_conf_file);
    zg = zlog_get_category("client_debug");
    
    iniparser_get(&conf_file, &port, serverip, sizeof(serverip));
    get_device_id(device_id, sizeof(device_id));//获取ID;
      
    if ( !serverip || !port )
    {
	    printf("error:ip and port get failed:%s\n", strerror(errno));
        zlog_debug(zg, "error:ip and port get failed,zlog_debug");
	    return -1;
    }

    if ((database_init(&db, db_file)) != 0)
    {
	   // printf("open create table error\n");
        zlog_debug(zg, "open create table error,zlog_debug");
	    return -2;
    }

    last_time = 0;

    while(!sig_stop)
    {   
        time(&now_time);
        if ((now_time - last_time) >= 5)
        {
            last_time = now_time;
            ds18b20(&tmp);
        }
        if (connfd < 0)
        {
            connfd = socket_connect(serverip, port);
            if ( connfd < 0 )
            {
                if ((save_data(db, &tmp, device_id)) != 0)
                {
                  //  printf("save data to sqlite3 failed\n");
                    zlog_debug(zg, "save data to sqlite3 failed,zlog_debug");
                    return -5;
                }
                sleep(2);

            }
            else if (connfd > 0)
            {
                rv = pack_json(buf, sizeof(buf), device_id, tmp);
                sleep(2);
                if (rv < 0)
                {
                  //  printf("pack the data failed\n");
                    zlog_debug(zg, "pack the data failed,zlog_debug");
                    return -3;
                }
                printf("The client connectes to server and sends data......\n");
                if( write(connfd, buf, sizeof(buf)) < 0 )
                {
                    printf("Write data to server [%s:%d] failure: %s\n",serverip,port,strerror(errno));
                    zlog_debug(zg, "Write data to server failed,zlog_debug");
                    if ((save_data(db, &tmp, device_id)) != 0)
                    {
                      //  printf("save data to sqlite3 failed\n");
                        zlog_debug(zg, "save data to sqlite3 failed when writting to server,zlog_debug");
                        return -4;
                    }
                    close(connfd);
                    connfd = -1;
                }
                //发送保存在数据库里的数据；
                if ((get_nrow(db, number)) != 0)
                { 
                  //  printf ("get the nrow error\n");
                    zlog_debug(zg, "get the nrow error,zlog_debug");
                    return -6;
                }

                if (number == 0)//number为0则数据库无数据，不做下面任何操作；
                {
                    break;
                }
                else
                {
                    len = *number <= 10 ? *number : 10 ;
                    for(i=1; i<len+1; i++)
                    {

                        if ((get_data(db, &tmp, device_id)) != 0 )
                        {
                           // printf("get data from sqlite3 error\n");
                            zlog_debug(zg, "get data from sqlite3 error,zlog_debug");
                        }

                        rv = pack_json(buf, sizeof(buf), device_id, tmp);
                        sleep(2);
                        if (rv < 0)
                        {
                           // printf("pack the data failed\n");
                            zlog_debug(zg, "pack the data failed,zlog_debug");
                            return -7;
                        }

                        if( write(connfd, buf, sizeof(buf)) < 0 )
                        {
                            printf("Write data to server [%s:%d] failure: %s\n", serverip, port, strerror(errno));
                            zlog_debug(zg, "Write data to server failure,zlog_debug");
                            close(connfd);
                            connfd = -1;
                            return -8;
                        }
                        if ((get_rowid(db)) != 0)
                        {
                           // printf(" get rowid error!\n");
                            zlog_debug(zg, "get rowid error,zlog_debug");

                        }
                        printf ("get the rowid ok\n");
                        if ((delete_data(db, rowid)) != 0)
                        {
                         //   printf("delete data error\n");
                            zlog_debug(zg, "delete data error,zlog_debug");
                            return -9;
                        }
                        rowid++;
                    }
                }
                sqlite3_close(db);
            }
        
    close(connfd);
      connfd = -1;
        }
    }
    zlog_fini();
    return 0;
}

